package com.zhiwei.controller;

import com.zhiwei.configuration.SysConf;
import com.zhiwei.pojo.*;
import com.zhiwei.service.*;
import com.zhiwei.tool.BillUtil;
import com.zhiwei.tool.TipGener;
import com.zhiwei.tool.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.*;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/download")
public class DownloadController {
    @Autowired
    SysConf sysConf;
    @Autowired
    private BillService billService;//发票
    @Autowired
    private ProductsService productsService; //商品
    @Autowired
    private OrderService orderService; //订单
    @Autowired
    private UserService userService; //用户
    @Autowired
    private TraderService traderService; //供应商，客户

    @GetMapping("/tip/{orderId}/{userId}")
    public void downLoad(@PathVariable Integer orderId, @PathVariable Integer userId, HttpServletResponse response) throws Exception {
        log.info(orderId + "----" + userId);
        //获取订单详情
        Order order = orderService.getOrder(orderId);
        //获取经手人信息
        User dealer = userService.getUser(userId);
        //获取销售人信息
        User sealer = userService.getUser(order.getOperId());
        //获取产品
        Products product = productsService.getProduct(order.getProductId());
        //生成发票信息
        Bill bill = billService.selectByOrderId(orderId);
        if (bill == null) {
            bill = BillUtil.BillGener(order, dealer, product, sealer);
        }
        // 获取交易方id 后 获取交易方信息
        Trader trader = traderService.getTrader(order.getTraderId());
        //获取本公司信息
        Trader ourCompany = traderService.getTrader(1);
        //生成发票流的方法
        File file = TipGener.getInvoice(sysConf.getFilePath() + "/tipFiles/", order, bill, product, trader, ourCompany, sealer, dealer);
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("tip.pdf", "UTF-8"));
            response.addHeader("Content-Length", "" + file.length());
//            response.setContentType("application/octet-stream");
            outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException e) {
            log.warn("正在下载发票...");
//            e.printStackTrace();
        } finally {
            Bill oldBill = billService.selectByOrderId(bill.getOrderId());
            if (oldBill == null) {
                billService.addBill(bill);
            } else {
                billService.updateBill(bill);
            }
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                log.warn("下载完成...你的主机中的软件中止了一个已建立的连接!");
//                e.printStackTrace();
            }
        }
    }

    @GetMapping("/img/**")
    public void getImg(HttpServletRequest request, HttpServletResponse response) {
        File file = new File(sysConf.getFilePath() + request.getRequestURI());
        try {
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            response.addHeader("Content-Length", String.valueOf(file.length()));
            response.setContentType(MediaType.IMAGE_PNG_VALUE);
            Utils.transStream(new FileInputStream(file), response.getOutputStream());
        } catch (IOException e) {
            log.warn("获取图片异常...", e);
        }
    }
}
